<?php
namespace App\Controller;
use Common\Controller\AppbusinessbaseController;
use Common\Controller\AppbusinessdobaseController;
use Think\Exception;
use Think\Model;

class BusinessController extends AppbusinessbaseController {
    /**
     * 此类是商户审核未通过就可以调用的类
     */

    /**
     * 获取商家二维码
     */
    public function getBusinessErweima(){
        $data['erweima']=$this->uploadPre.$this->business['erweima'];
        $data['logo']=empty($this->business['logo'])?'':$this->uploadPre.$this->business['logo'];
        $data['company']=$this->business['company'];
        $data['phone']=empty($this->business['phone'])?'':$this->business['phone'];
        $this->jsonUnslashesReturn(1,'获取成功',$data);
    }

    /**
     *  意见反馈
     */
    public function advice(){
        $content=I('content');
        if(!$content){
            $this->jsonReturn(0,'内容必填');
        }
        $data['content']=$content;
        $data['user_id']=$this->businessId;
        $data['type']=1;
        $data['create_time']=time();
        $result=M('Advice')->add($data);
        if($result!==false){
            $this->jsonReturn(1,'添加成功');
        }else{
            $this->jsonReturn(0,'建议添加失败');
        }
    }

    /**
     *  退出登录
     */
    public function logout(){
        $result=M('Business')->where(['id'=>$this->businessId])->save(['token'=>'']);
        if($result!==false){
            $this->jsonReturn(1,'退出成功');
        }else{
            $this->jsonReturn(0,'退出失败');
        }
    }


    /**
     * 更换手机号
     */
    public function changePhone(){
        $oldPhone=$this->business['phone'];
        $oldPhoneSms=I('oldPhoneSms');
        $newPhone=I('newPhone');
        $newPhoneSms=I('newPhoneSms');
        if(!$oldPhoneSms||!$newPhone||!$newPhoneSms){
            $this->jsonReturn(0,'验证码和电话号必填');
        }
        if(!lt_is_telephone($oldPhone) || !lt_is_telephone($newPhone)){
            $this->jsonReturn(0,'电话格式不正确');
        }
        if($oldPhone==$newPhone){
            $this->jsonReturn(0,'电话相同，无需更换');
        }
        $checkPhone=M('Business')->where(['phone'=>$newPhone])->field('id')->find();
        if($checkPhone){
            $this->jsonReturn(0,'电话已存在');
        }
        $this->checkPhoneCode($oldPhone,$oldPhoneSms);
        $this->checkPhoneCode($newPhone,$newPhoneSms);
        $result=M('Business')->where(['id'=>$this->businessId])->save(['phone'=>$newPhone]);
        if($result!==false){
            $this->jsonReturn(1,'修改成功');
        }else{
            $this->jsonReturn(0,'修改失败');
        }
    }

    //获取店铺排行列表
    public function getBusinessRank(){
        $lat=I('lat');
        $long=I('lng');
        $page=I('page',0,'intval');
        if(!$lat||!$long||$page<=0){
            $this->jsonReturn(0,'请开启定位');
        }
        $start=($page-1)*$this->pageLimit;
        //获取城市名和id
        $region=$this->getSite($lat,$long);
        $region_id=$region['id'];
        //获取城市下区域id
        $region_ids=M('Region')->where(['pid'=>$region_id])->select();
        $region_ids=array_column($region_ids,'id');
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $businesses=M('Business')
            ->alias('b')
            ->where(['b.status'=>1,'b.is_checked'=>1,'region_id'=>['in',$region_ids]])
            ->join('LEFT JOIN __REGION__ as r ON r.id=b.region_id')
            ->field("b.id,b.type,r.name as city,b.name,points,logo,good_at,collect_num,visit_num,$sql as distance,visit")
            ->order('points DESC,distance')->limit($start,$this->pageLimit+1)->select();
        if($businesses){
            //加前缀,默认商家logo
            foreach ($businesses as &$business){
                $business['logo']=empty($business['logo'])?"":$this->uploadPre.$business['logo'];
                $business['city']=$region['name'].$business['city'];
            }
            if($page==1){
                $re=M('Region')->where(['id'=>$this->business['region_id']])->find();
                $pre=M('Region')->where(['id'=>$re['pid']])->find();
                $pre=empty($pre)?"":$pre['name'];
                $self=['id'=>$this->business['id'],'type'=>$this->business['type']
                    ,'city'=>$pre.$re['name']
                    ,'name'=>$this->business['name']
                    ,'points'=>$this->business['points']
                    ,'logo'=>empty($this->business['logo'])?"":$this->uploadPre.$this->business['logo']
                    ,'good_at'=>$this->business['good_at']
                    ,'collect_num'=>$this->business['collect_num']
                    ,'visit_num'=>$this->business['visit_num']
                    ,'distance'=>0
                    ,'visit'=>$this->business['visit']];
                array_unshift($businesses,$self);
            }
            //检测是否是最后一页
            $businesses=$this->checkEndPage($businesses);
            $this->jsonUnslashesReturn(1,'获取成功',$businesses);
        }else{
            $this->jsonReturn(1,'没有商家了',(object)[]);
        }
    }

    //获取店铺排行店铺信息详情
    public function getBusinessRankData(){
        $lat=I('lat');
        $long=I('lng');
        $id=I('id',0,'intval');
        if(!$lat||!$long||!$id){
            $this->jsonReturn(0,'请开启定位');
        }
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $business=M('Business')->where(['id'=>$id,'status'=>1,'is_checked'=>1])->field("id,type,name,points,good_at,collect_num,visit_num,$sql as distance,address,phone,acreage,people_number,years,advantage,lat,`long` as lng,create_time")->find();
        if($business){
            $this->jsonReturn(1,'获取成功',$business);
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取店铺排行商家轮播图
     */
    public function getBusinessRankSlides(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $slides=M('BusinessSlide')->where(['business_id'=>$id])->field('image')->select();
            if($slides){
                foreach ($slides as &$slide){
                    $slide['image']=empty($slide['image'])?'':$this->uploadPre.$slide['image'];
                }
                $this->jsonUnslashesReturn(1,'获取成功',$slides);
            }else{
                $this->jsonUnslashesReturn(1,'获取成功',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取店铺排行商户技师
     */
    public function getBusinessRankTech(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $technicians=M('BusinessTech')->where(['business_id'=>$id])->field('name,avatar')->select();
            if($technicians){
                foreach ($technicians as &$technician){
                    $technician['avatar']=empty($technician['avatar'])?"":$this->uploadPre.$technician['avatar'];
                }
                $this->jsonUnslashesReturn(1,'获取成功',$technicians);
            }else{
                $this->jsonUnslashesReturn(1,'还没添加技师',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取店铺排行商户全部服务
     */
    public function getBusinessRankServices(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $businessServices=M('BusinessService')->where(['business_id'=>$id,'is_deleted'=>0])->field('price,name,good_at,id')->select();
            if($businessServices){
                $this->jsonReturn(1,'获取成功',$businessServices);
            }else{
                $this->jsonReturn(1,'没有服务',[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 获取店铺排行商户活动
     */
    public function getBusinessRankActivity(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($id);
        if($business){
            $businessActivity=M('BusinessActivity')->where(['business_id'=>$id,'is_deleted'=>0,'end_time'=>['EGT',time()]])
                ->order('end_time')->field('id,price,name,inventory,start_time,end_time')->find();
            if($businessActivity){
                $businessActivityContent=M('BusinessActivityContent')->where(['business_id'=>$id])->field('content,image')->find();
                if(!$businessActivityContent){
                    $businessActivity['content']='';
                    $businessActivity['image']='';
                }else{
                    $businessActivity['content']=empty($businessActivityContent['content'])?'':$businessActivityContent['content'];
                    $businessActivity['image']=empty($businessActivityContent['image'])?'':$this->uploadPre.$businessActivityContent['image'];
                }
                $this->jsonUnslashesReturn(1,'获取成功',$businessActivity);
            }else{
                $this->jsonReturn(1,'还没有服务',(object)[]);
            }
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 店铺排行服务详情关于商户部分
     */
    public function getRankServiceDetailsAboutBusiness(){
        $id=I('id',0,'intval');
        $lat=I('lat');
        $long=I('lng');
        if(!$id||!$lat||!$long){
            $this->jsonReturn(0,'请开启定位');
        }
        //获取距离排序sql
        $sql=$this->getDistanceSql($lat,$long);
        $business=M('Business')->where(['id'=>$id,'status'=>1,'is_checked'=>1])->field("id,name,points,visit,$sql as distance,address,phone,lat,`long` as lng")->find();
        if($business){
            $this->jsonReturn(1,'获取成功',$business);
        }else{
            $this->jsonReturn(0,'无此商家或该商家已被禁用');
        }
    }

    /**
     * 店铺排行服务详情关于轮播部分
     */
    public function getRankServiceDetailsAboutBanner(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'参数不存在');
        }
        $service=M('BusinessService')->where(['id'=>$id])->field("id,name,price,order_number")->find();
        if($service){
            $slides=M('BusinessServiceImage')->where(['business_service_id'=>$id,'type'=>1])->select();
            if($slides){
                //分割轮播和底部图
                foreach ($slides as $slide){
                    $service['banner'][]=['image'=>$this->uploadPre.$slide['image']];
                }
            }else{
                $service['banner']=[];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$service);
        }else{
            $this->jsonReturn(0,'无此服务');
        }
    }

    /**
     * 店铺排行服务详情关于底部部分
     */
    public function getRankServiceDetailsAboutFooter(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'参数不存在');
        }
        $service=M('BusinessService')->where(['id'=>$id])->field("id,content")->find();
        if($service){
            $slides=M('BusinessServiceImage')->where(['business_service_id'=>$id,'type'=>2])->select();
            if($slides){
                //分割轮播和底部图
                foreach ($slides as $slide){
                    $service['footer'][]=['image'=>$this->uploadPre.$slide['image']];
                }
            }else{
                $service['footer']=[];
            }
            $this->jsonUnslashesReturn(1,'获取成功',$service);
        }else{
            $this->jsonReturn(0,'无此服务');
        }
    }

    /**
     * 店铺排行服务评价
     */
    public function getRankServiceComments(){
        $id=I('id',0,'intval');
        $page=I('page',0,'intval');
        if(!$id||$page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $comments=M('BusinessServiceComment')->where(['business_service_id'=>$id])
            ->field("username,avatar,star,content")->order('create_time DESC')->limit($start,$this->pageLimit+1)->select();
        if($comments){
            foreach ($comments as &$comment){
                $comment['avatar']=empty($comment['avatar'])?'':$this->uploadPre.$comment['avatar'];
            }
            //检测是否是最后一页
            $comments=$this->checkEndPage($comments);
            $this->jsonUnslashesReturn(1,'获取成功',$comments);
        }else{
            $this->jsonReturn(1,'暂无评价',(object)[]);
        }
    }

    /**
     * 写经营总结
     */
    public function addSummary(){
        $data['title']=I('title');
        $data['content']=I('content');
        if(!$data['title']||!$data['content']){
            $this->jsonReturn(0,'标题和内容必填');
        }
        $time=time();
        $data['create_time']=$time;
        $data['update_time']=$time;
        $data['business_id']=$this->businessId;
        $result=M('BusinessSummary')->add($data);
        if($result!==false){
            $this->jsonReturn(1,'添加成功');
        }else{
            $this->jsonReturn(0,'添加失败');
        }
    }

    /**
     * 修改经营总结
     */
    public function editSummary(){
        $id=I('id');
        $data['title']=I('title');
        $data['content']=I('content');
        if(!$data['title']||!$data['content']||!$id){
            $this->jsonReturn(0,'标题和内容必填');
        }
        $data['update_time']=time();
        $summary=M('BusinessSummary')->where(['business_id'=>$this->businessId,'id'=>$id])->find();
        if($summary){
            $result=M('BusinessSummary')->where(['id'=>$id])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'修改成功');
            }else{
                $this->jsonReturn(0,'修改失败');
            }
        }else{
            $this->jsonReturn(0,'总结不存在');
        }
    }

    /**
     * 删除经营总结
     */
    public function deleteSummary(){
        $id=I('id');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $summary=M('BusinessSummary')->where(['business_id'=>$this->businessId,'id'=>$id])->find();
        if($summary){
            $result=M('BusinessSummary')->where(['id'=>$id])->delete();
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'总结不存在');
        }
    }

    /**
     * 获取总结列表
     */
    public function getSummaries(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $summaries=M('BusinessSummary')->where(['business_id'=>$this->businessId])
            ->field("title,create_time,id")->order('create_time DESC')->limit($start,$this->pageLimit+1)->select();
        if($summaries){
            //检测是否是最后一页
            $summaries=$this->checkEndPage($summaries);
            $this->jsonReturn(1,'获取成功',$summaries);
        }else{
            $this->jsonReturn(1,'暂无评价',(object)[]);
        }
    }

    /**
     * 获取总结详情
     */
    public function getSummaryDetails(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $summary=M('BusinessSummary')->where(['business_id'=>$this->businessId,'id'=>$id])->field('title,content')->find();
        if($summary){
            $this->jsonReturn(1,'获取成功',$summary);
        }else{
            $this->jsonReturn(0,'总结不存在');
        }
    }

    /**
     * 记账
     */
    public function setAccount(){
        $data=$_POST['data'];
        $data=json_decode($data,true);
        $time=time();
        if(!$data[0]['time']){
            $this->jsonReturn(0,'时间必填');
        }
        if(!$data[0]['price']){
            $this->jsonReturn(0,'金额必填');
        }
        if(!$data[0]['type']||!$data[0]['remark']){
            $this->jsonReturn(0,'备注必填');
        }
        //type2是支出，直接存负值
        foreach ($data as &$value){
            if($value['type']==2){
                $value['price']=-abs(intval($value['price']));
            }else{
                $value['price']=abs(intval($value['price']));
            }
            $value['create_time']=$time;
            $value['business_id']=$this->businessId;
        }
        //开启事物
        M('BusinessAccount')->startTrans();
        try {
            //插入账单表
            $result=M('BusinessAccount')->addAll($data);
            if ($result === false) {
                throw new Exception('添加失败！');
            }
            //插入金钱记录表
            foreach ($data as $k=>$item){
                $dataPrice[$k]['user_id']=($item['price']>0)?0:$this->businessId;
                $dataPrice[$k]['receive_user_id']=($item['price']>0)?$this->businessId:0;
                $dataPrice[$k]['price']=abs($item['price']);
                $dataPrice[$k]['create_time']=$time;
                $dataPrice[$k]['type']=2;
                $dataPrice[$k]['category']=4;
            }
            $result = M('PriceLog')->addAll($dataPrice);
            if ($result === false) {
                throw new Exception('插入记录表失败！');
            }
            M('BusinessAccount')->commit();
            $this->jsonReturn(1,'添加成功');
        } catch (Exception $e) {
            M('BusinessAccount')->rollback();
            $this->jsonReturn(0,$e->getMessage());
        }
    }

    /**
     * 记账收入和支出
     */
    public function getAccountTotal(){
        $in=M('BusinessAccount')->where(['business_id'=>$this->businessId,'price'=>['GT',0]])->sum('price');
        $out=M('BusinessAccount')->where(['business_id'=>$this->businessId,'price'=>['ELT',0]])->sum('price');
        $in=empty($in)?0:$in;
        $out=empty($out)?0:-$out;
        $this->jsonReturn(1,'获取成功',['in'=>"$in",'out'=>"$out"]);
    }

    /**
     * 获取账本
     */
    public function getAccounts(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $accounts=M('BusinessAccount')->where(['business_id'=>$this->businessId])->field('price,time,remark')
            ->order('create_time DESC,id')->limit($start,$this->pageLimit+1)->select();
        if($accounts){
            //检测是否是最后一页
            $accounts=$this->checkEndPage($accounts);
            $this->jsonReturn(1,'获取成功',$accounts);
        }else{
            $this->jsonReturn(1,'没有记账',(object)[]);
        }
    }

    //获取起止日期每天/月的数组,type1按日分，2按月分
    private function getTimeByType($start,$end,$type=1){
        if($type==1){
            $start=strtotime(date("Y-m-d",$start));
            $end=strtotime(date("Y-m-d",$end));
            $differ=$end-$start;
            if($differ<0){
                return false;
            }
            $one_day=60*60*24;
            $day=$differ/$one_day;
            $d=[];
            for ($i=0;$i<=$day;$i++){
                $d[]=$start+$i*$one_day;
            }
            return $d;
        }else{
            $start=strtotime(date("Y-m-d",$start));
            $end=strtotime(date("Y-m-d 23:59:59",$end));
            if($end-$start<0){
                return false;
            }
            $monarr = array();
            $monarr[] = $start; // 当前月;
            while( ($start = strtotime('+1 month', $start)) <= $end){
                $monarr[] = strtotime(date('Y-m-1',$start)); // 取得递增月;
            }
            $monarr[]=$end;
            return $monarr;
        }
    }

    //曲线数据
    public function getCurve(){
        $start=I('start',0,'intval');
        $end=I('end',0,'intval');
        $type=I('type',1,'intval');
        if(!$start||!$end||!$type){
            $this->jsonReturn(0,'时间必须');
        }
        if(date("Y",$start)!=date("Y",$end)){
            $this->jsonReturn(0,'只能选择同一年的数据');
        }
        $days=$this->getTimeByType($start,$end,$type);
        if(!$days){
            $this->jsonReturn(0,'参数错误');
        }
        //用户端金钱记录
        $logs=M('PriceLog')
            ->where(['receive_user_id'=>$this->businessId,'create_time'=>['between',[$start,$end]]])
            ->field('create_time,price,category,id')
            ->select();
        if($logs){
            if($type==1){
                $result=$this->getDayCurve($logs,$days);
            }else{
                $result=$this->getMonthCurve($logs,$days);
            }
            $this->jsonReturn(1,'获取成功',$result);
        }else{
            $this->jsonReturn(1,'没有支出',[]);
        }
    }

    /**
     * 根据日期分组
     * @param $logs
     * @param $days
     * @return array
     */
    private function getDayCurve($logs,$days){
        $result=[];
        //按每天分组
        foreach ($days as $day){
            foreach ($logs as $log){
                if($day==strtotime(date("Y-m-d",$log['create_time']))){
                    $result[$day][]=$log;
                }
            }
        }
        foreach ($result as $kk=>&$value){
            $total=0;
            $online=0;
            $outline=0;
            $sao=0;
            foreach ($value as $k=>$v){
                switch ($v['category']){
                    case 1 : $online+=$v['price'];break;
                    case 2 : $sao+=$v['price'];break;
                    case 3 : $outline+=$v['price'];break;
                }
                $total+=$v['price'];
                unset($value[$k]);
            }
            $value['total']=sprintf("%.2f",$total);
            $value['online']=sprintf("%.2f",$online);
            $value['outline']=sprintf("%.2f",$outline);
            $value['sao']=sprintf("%.2f",$sao);
            $value['time']= "$kk";
        }
        //补全数组,1线上，2扫码，3线下，4记账
        $keys=array_keys($result);
        $array_diff=array_diff($days,$keys);
        if($array_diff){
            foreach ($array_diff as $item){
                $result[$item]=['total'=>'0.00','online'=>'0.00','outline'=>'0.00','sao'=>'0.00','time'=>"$item"];
            }
        }
        ksort($result);
        $result=array_values($result);
        return $result;
    }

    /**
     * 根据月份分组
     * @param $logs
     * @param $days
     * @return array
     */
    private function getMonthCurve($logs,$days){
        $result=[];
        //按每天分组
        foreach ($logs as $log){
            foreach ($days as $dk=>$day){
                if($day>strtotime(date("Y-m-d",$log['create_time']))){
                    $result[$days[$dk-1]][]=$log;
                    break;
                }
            }
        }
        array_pop($days);
        foreach ($result as $kk=>&$value){
            $total=0;
            $online=0;
            $outline=0;
            $sao=0;
            foreach ($value as $k=>$v){
                switch ($v['category']){
                    case 1 : $online+=$v['price'];break;
                    case 2 : $sao+=$v['price'];break;
                    case 3 : $outline+=$v['price'];break;
                }
                $total+=$v['price'];
                unset($value[$k]);
            }
            $value['total']=sprintf("%.2f",$total);
            $value['online']=sprintf("%.2f",$online);
            $value['outline']=sprintf("%.2f",$outline);
            $value['sao']=sprintf("%.2f",$sao);
            $value['time']=strval(strtotime(date("Y-m",$kk)));
        }
        //补全数组,1线上，2扫码，3线下，4记账
        $keys=array_keys($result);
        $array_diff=array_diff($days,$keys);
        if($array_diff){
            foreach ($array_diff as $item){
                $result[$item]=['total'=>'0.00','online'=>'0.00','outline'=>'0.00','sao'=>'0.00','time'=>strval(strtotime(date("Y-m",$item)))];
            }
        }
        ksort($result);
        $result=array_values($result);
        return $result;
    }

    //盈利金额
    public function getOrderTotal(){
        $orderTotal=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->where(['bs.business_id'=>$this->businessId,'o.status'=>['neq',0]])
            ->sum('o.total');
        $orderTotal=$orderTotal?intval($orderTotal):0;
        $orderActivityTotal=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->where(['ba.business_id'=>$this->businessId,'o.status'=>['neq',0]])
            ->sum('o.total');
        $orderActivityTotal=$orderActivityTotal?intval($orderActivityTotal):0;
        $total=$orderTotal+$orderActivityTotal;
        $this->jsonReturn(1,'获取成功',strval($total));
    }

    //获取时间段内订单信息,服务订单/活动订单/需求订单
    public function getOrdersByTime(){
        $start_time=I('start_time',0,'intval');
        $end_time=I('end_time',0,'intval');
        $page=I('page',0,'intval');
        if(!$start_time||!$end_time||!$page){
            $this->jsonReturn(0,'时间必须');
        }
        $orders=$this->getUnionOrders($start_time,$end_time,$page);
        if($orders){
            $orderCount=$this->getUnionOrderCount($start_time,$end_time);
            $orderActivityCount=$this->getUnionOrderActivityCount($start_time,$end_time);
            $count=$orderCount+$orderActivityCount;
            $orderSum=$this->getUnionOrderSum($start_time,$end_time);
            $orderActivitySum=$this->getUnionOrderActivitySum($start_time,$end_time);
            $sum=$orderSum+$orderActivitySum;
            $onlineOrderSum=$this->getUnionOnlineOrderSum($start_time,$end_time);
            $onlineOrderActivitySum=$this->getUnionOnlineOrderActivitySum($start_time,$end_time);
            $onlineSum=$onlineOrderSum+$onlineOrderActivitySum;
            $orders=$this->checkEndPage($orders);
            $orders['count']=strval($count);
            $orders['sum']=strval($sum);
            $orders['onlineSum']=strval($onlineSum);
            $this->jsonReturn(1,'获取成功',$orders);
        }else{
            $this->jsonReturn(1,'没有数据',['is_end'=>1,'list'=>[],'count'=>0,'sum'=>0,'onlineSum'=>0]);
        }
    }

    /**
     * 获取union的订单
     * @param $start_time
     * @param $end_time
     * @param $page
     * @return mixed
     */
    private function getUnionOrders($start_time,$end_time,$page){
        $start=($page-1)*$this->pageLimit;
        $Model = new Model();
        $orders=$Model
            ->table('yh_order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->join('LEFT JOIN __USER__ as u ON u.id=o.user_id')
            ->field('total,paid_time,payment,business_service_name as name,username')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'o.status'=>['neq',0],'business_id'=>$this->businessId])
            ->union('SELECT total,paid_time,payment,ba.`name`,username FROM yh_order_activity as oa LEFT JOIN yh_business_activity as ba ON ba.id=oa.business_activity_id LEFT JOIN yh_user as u ON u.id=oa.user_id where paid_time BETWEEN '.$start_time.' AND '.$end_time.' AND oa.`status` <> 0 AND `business_id`='.$this->businessId.' ORDER BY `paid_time` DESC LIMIT '.$start.','.($this->pageLimit+1))
            ->select();
        return $orders;
    }

    /**
     * 获取服务订单数量
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOrderCount($start_time,$end_time){
        $orderCount=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->field('paid_time')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId])
            ->count();
        $orderCount=empty($orderCount)?0:intval($orderCount);
        return $orderCount;
    }

    /**
     * 获取服务订单数量
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOrderActivityCount($start_time,$end_time){
        $orderActivityCount=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as bs ON bs.id=o.business_activity_id')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId])
            ->count();
        $orderActivityCount=empty($orderActivityCount)?0:intval($orderActivityCount);
        return $orderActivityCount;
    }

    /**
     * 获取服务订单总价
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOrderSum($start_time,$end_time){
        $orderSum=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->field('paid_time')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId])
            ->sum('total');
        $orderSum=empty($orderSum)?0:intval($orderSum);
        return $orderSum;
    }

    /**
     * 获取活动订单总价
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOrderActivitySum($start_time,$end_time){
        $orderActivitySum=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as bs ON bs.id=o.business_activity_id')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId])
            ->sum('total');
        $orderActivitySum=empty($orderActivitySum)?0:intval($orderActivitySum);
        return $orderActivitySum;
    }

    /**
     * 获取服务订单在线总价
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOnlineOrderSum($start_time,$end_time){
        $orderSum=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->field('paid_time')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId,'payment'=>['neq',3]])
            ->sum('total');
        $orderSum=empty($orderSum)?0:intval($orderSum);
        return $orderSum;
    }

    /**
     * 获取活动订单在线总价
     * @param $start_time
     * @param $end_time
     * @return int
     */
    private function getUnionOnlineOrderActivitySum($start_time,$end_time){
        $orderActivitySum=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as bs ON bs.id=o.business_activity_id')
            ->where(['paid_time'=>['between',[$start_time,$end_time]],'status'=>['neq',0],'business_id'=>$this->businessId,'payment'=>['neq',3]])
            ->sum('total');
        $orderActivitySum=empty($orderActivitySum)?0:intval($orderActivitySum);
        return $orderActivitySum;
    }

    //收入明细
    public function getIncomeDetails(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $where['_string'] = 'receive_user_id='.$this->businessId.' OR user_id='.$this->businessId;
        $logs=M('PriceLog')
            ->where($where)
            ->field('category,price,create_time,user_id')
            ->order(['create_time DESC'])
            ->limit($start,$this->pageLimit+1)
            ->select();
        if($logs){
            foreach ($logs as &$log){
                if($log['user_id']==$this->businessId){
                    $log['price']=sprintf('%.2f',-$log['price']);
                }
                unset($log['user_id']);
            }
            $logs=$this->checkEndPage($logs);
            $this->jsonReturn(1,'获取成功',$logs);
        }else{
            $this->jsonReturn(1,'没有收支明细',(object)[]);
        }
    }
}